package com.avic.modules.system.service.impl;

import cn.hutool.core.date.DateUtil;
import com.avic.common.service.impl.BaseServiceImpl;
import com.avic.common.utils.QueryHelpPlus;
import com.avic.dozer.service.IGenerator;
import com.avic.exception.BadRequestException;
import com.avic.modules.log.domain.vo.LogEnumeration;
import com.avic.modules.log.domain.vo.LogVo;
import com.avic.modules.log.service.LogsService;
import com.avic.modules.log.utils.ContrastObjUtil;
import com.avic.modules.system.domain.*;
import com.avic.modules.system.domain.vo.UserVo;
import com.avic.modules.system.service.*;
import com.avic.modules.system.service.dto.UserDto;
import com.avic.modules.system.service.dto.UserQueryCriteria;
import com.avic.modules.system.service.mapper.*;
import com.avic.tools.config.bean.AvicConfigElement;
import com.avic.tools.utils.ExcelBean;
import com.avic.tools.utils.ExcelParser;
import com.avic.utils.FileUtil;
import com.avic.utils.RedisUtils;
import com.avic.utils.SecurityUtils;
import com.avic.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.poifs.filesystem.OfficeXmlFileException;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.data.domain.Pageable;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.sql.Timestamp;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author zhangzikang
 * @date 2022-08-14
 */
@Service
@ConditionalOnMissingBean(AvicConfigElement.class)
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class SysUserServiceImpl extends BaseServiceImpl<SysUserMapper, User> implements UserService {

    private final AvicConfigElement avicConfigElement;
    private final IGenerator generator;
    private final SysUserMapper userMapper;
    private final UserAvatarService userAvatarService;
    private final JobService jobService;
    private final DeptService deptService;
    private final RoleMapper roleMapper;
    private final RedisUtils redisUtils;
    private final UsersRolesService usersRolesService;
    private final DeptMapper deptMapper;
    private final JobMapper jobMapper;
    private final WorkshopSectionMapper workshopSection;
    private final LogsService logsService;
    private final UsersRolesMapper usersRolesMapper;
    private final PasswordEncoder passwordEncoder;
    private final WorkshopSectionMapper workshopSectionMapper;


    public SysUserServiceImpl(AvicConfigElement avicConfigElement, IGenerator generator, SysUserMapper userMapper, UserAvatarService userAvatarService, JobService jobService, DeptService deptService, RoleMapper roleMapper, RedisUtils redisUtils, UsersRolesService usersRolesService,
                              DeptMapper deptMapper, JobMapper jobMapper, WorkshopSectionMapper workshopSection, LogsService logsService, UsersRolesMapper usersRolesMapper, PasswordEncoder passwordEncoder, WorkshopSectionMapper workshopSectionMapper) {
        this.avicConfigElement = avicConfigElement;
        this.generator = generator;
        this.userMapper = userMapper;
        this.userAvatarService = userAvatarService;
        this.jobService = jobService;
        this.deptService = deptService;
        this.roleMapper = roleMapper;
        this.redisUtils = redisUtils;
        this.usersRolesService = usersRolesService;
        this.deptMapper = deptMapper;
        this.jobMapper = jobMapper;
        this.workshopSection = workshopSection;
        this.logsService = logsService;
        this.usersRolesMapper = usersRolesMapper;
        this.passwordEncoder = passwordEncoder;
        this.workshopSectionMapper = workshopSectionMapper;
    }

    @Override
    public Map<String, Object> queryAll(UserQueryCriteria criteria, Pageable pageable) {
        if(criteria.getDeptName()!=null&&criteria.getDeptName()!=""){
            QueryWrapper<Dept> wrapper = new QueryWrapper<>();
            wrapper.like("name",criteria.getDeptName());
            List<Dept> jobs = deptMapper.selectList(wrapper);
            List<Long> js = new ArrayList<>();
            for(Dept jos:jobs){
                js.add(jos.getId());
            }
            if(jobs.size()==0){
                js.add(0L);
            }
            criteria.setDeptNames(js);
        }
        if(criteria.getJobName()!=null&&criteria.getJobName()!=""){
            QueryWrapper<Job> wrapper = new QueryWrapper<>();
            wrapper.like("name",criteria.getJobName());
            List<Job> jobs = jobMapper.selectList(wrapper);
            List<Long> js = new ArrayList<>();
            if(jobs.size()==0){
                long zl = 0;
                js.add(zl);
            }else {
                for(Job job:jobs){
                    js.add(job.getId());
                }
            }
            criteria.setJobIds(js);
        }
        if(criteria.getWorkName()!=null&&criteria.getWorkName()!=""){
            QueryWrapper<WorkshopSection> wrapper = new QueryWrapper<>();
            wrapper.like("name",criteria.getWorkName());
            List<WorkshopSection> jobs = workshopSectionMapper.selectList(wrapper);
            List<String> js = new ArrayList<>();
            if(jobs.size()==0){
                js.add("我");
            }else {
                for(WorkshopSection jos:jobs){
                    js.add(jos.getId());
                }
            }
            criteria.setWorkStages(js);
        }
        String order = "job_number desc";
        getPageSort(pageable,order);
        PageInfo<User> page = new PageInfo<>(queryAll(criteria));
        List<UserDto> convert = generator.convert(page.getList(), UserDto.class);
        for(UserDto user:convert){
            User user1= userMapper.selectById(user.getCreateUserId());
            if(user1!=null){
                user.setCreateUserName(user1.getNickName());
            }
            User user2 = userMapper.selectById(user.getUpdateUserId());
            if(user2!=null) {
                user.setUpdateUserName(user2.getNickName());
            }
        }
        Map<String, Object> map = new LinkedHashMap<>(2);
        map.put("content",convert);
        map.put("totalElements", page.getTotal());
        return map;
    }


    @Override
    public List<User> queryAll(UserQueryCriteria criteria) {
        List<User> userList = baseMapper.selectList(QueryHelpPlus.getPredicate(User.class, criteria));
        for (User user : userList) {
            Job job = jobMapper.selectById(user.getJobId());

            Dept dept = deptMapper.selectById(user.getDeptId());
            if(dept!=null){
                user.setDept(dept);
                user.setJob(job);
            }else {
                user.setDept(null);
                user.setDeptId(null);
                user.setJob(null);
                user.setJobId(null);
            }
            user.setRoles(roleMapper.findByUsers_Id(user.getId()));
            user.setParagraphs(workshopSection.selectById(user.getWorkStage()));
        }
        return userList;
    }

    @Override
    public List<User> queryAlls(UserQueryCriteria criteria, Pageable pageable) {
        if(criteria.getDeptName()!=null&&criteria.getDeptName()!=""){
            QueryWrapper<Dept> wrapper = new QueryWrapper<>();
            wrapper.like("name",criteria.getDeptName());
            List<Dept> jobs = deptMapper.selectList(wrapper);
            List<Long> js = new ArrayList<>();
            for(Dept jos:jobs){
                js.add(jos.getId());
            }
            criteria.setDeptNames(js);
        }
        if(criteria.getJobName()!=null&&criteria.getJobName()!=""){
            QueryWrapper<Job> wrapper = new QueryWrapper<>();
            wrapper.like("name",criteria.getJobName());
            List<Job> jobs = jobMapper.selectList(wrapper);
            List<Long> js = new ArrayList<>();
            if(jobs.size()==0){
                long zl = 0;
                js.add(zl);
            }else {
                for(Job job:jobs){
                    js.add(job.getId());
                }
            }
            criteria.setJobIds(js);
        }
        if(criteria.getWorkName()!=null&&criteria.getWorkName()!=""){
            QueryWrapper<WorkshopSection> wrapper = new QueryWrapper<>();
            wrapper.like("name",criteria.getWorkName());
            List<WorkshopSection> jobs = workshopSectionMapper.selectList(wrapper);
            List<String> js = new ArrayList<>();
            if(jobs.size()==0){
                js.add("我");
            }else {
                for(WorkshopSection jos:jobs){
                    js.add(jos.getId());
                }
            }
            criteria.setWorkStages(js);
        }
        String order = "job_number desc";
        getPageSize(pageable,order);
        List<User> userList = baseMapper.selectList(QueryHelpPlus.getPredicate(User.class, criteria));
        for (User user : userList) {
            Job job = jobMapper.selectById(user.getJobId());

            Dept dept = deptMapper.selectById(user.getDeptId());
            if(dept!=null){
                user.setDept(dept);
                user.setJob(job);
            }else {
                user.setDept(null);
                user.setDeptId(null);
                user.setJob(null);
                user.setJobId(null);
            }
            user.setRoles(roleMapper.findByUsers_Id(user.getId()));
            user.setParagraphs(workshopSection.selectById(user.getWorkStage()));
        }
        return userList;
    }


    @Override
    public void download(List<UserDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        long sum = 1;
        for (UserDto user : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("序号", sum);
            map.put("工号", user.getJobNumber());
            map.put("用户名", user.getUsername());
            map.put("姓名", user.getNickName());
            map.put("电话", user.getPhone());
            map.put("部门",user.getDept()!=null?user.getDept().getName():"");
            map.put("职位", user.getJob()!=null?user.getJob().getName():"");

            if(user.getParagraphs()==null){
                map.put("工段", "");
            }else {
                map.put("工段", user.getParagraphs().getName());
            }
            if(user.getEnabled() == false){
                map.put("登录状态", "禁用");
            }else {
                map.put("登录状态", "激活");
            }
            User user1= userMapper.selectById(user.getCreateUserId());
            if(user1!=null){
                map.put("创建人", user1.getNickName());
            } else {
                map.put("创建人", "");
            }
            if(user.getCreateTime()!=null){
                String s = user.getCreateTime().toString();
                String substring = s.substring(0, s.length() - 2);
                map.put("创建时间", substring);
            } else {
                map.put("创建时间", "");
            }

            User user2 = userMapper.selectById(user.getUpdateUserId());
            if(user2!=null) {
                map.put("修改人", user2.getNickName());
            } else {
                map.put("修改人", "");
            }
            if(user.getUpdateTime()!=null){
                String s = user.getUpdateTime().toString();
                String substring = s.substring(0, s.length() - 2);
                map.put("修改时间", substring);
            } else {
                map.put("修改时间", "");
            }
            sum ++;
            list.add(map);
        }
        // 创建操作日志
        LogVo logVo = new LogVo();
        String name = "[导出]了"+ "[用户信息]";
        logVo.setBehavior(name);
        logVo.setAction(LogEnumeration.LEADING_OUT.getMessage());
        logsService.save(logVo);
        FileUtil.downloadExcel(list, response);
    }

    /**
     * 根据用户名查询
     *
     * @param userName /
     * @return /
     */
    @Override
    public UserDto findByName(String userName) {
        User user = userMapper.findByName(userName);
        if(user!=null){
            //用户所属岗位
            user.setJob(jobService.getById(user.getJobId()));
            //用户所属部门
            user.setDept(deptService.getById(user.getDeptId()));
        }
        return generator.convert(user, UserDto.class);
    }

    /**
     * 修改密码
     *
     * @param username        用户名
     * @param encryptPassword 密码
     */
    @Override
    public void updatePass(String username, String encryptPassword) {
        userMapper.updatePass(encryptPassword, DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"), username);
    }

    /**
     * 修改头像
     *
     * @param multipartFile 文件
     */
    @Override
    public void updateAvatar(MultipartFile multipartFile) {
        User user = this.getOne(new LambdaQueryWrapper<User>()
                .eq(User::getUsername, SecurityUtils.getUsername()));
        UserAvatar userAvatar = userAvatarService.getOne(new LambdaQueryWrapper<UserAvatar>()
                .eq(UserAvatar::getId, user.getAvatarId()));
        String oldPath = "";
        if (userAvatar != null) {
            oldPath = userAvatar.getPath();
        } else {
            userAvatar = new UserAvatar();
        }
        String avatar = avicConfigElement.getAvatarLocation();

        File file = FileUtil.upload(multipartFile, avatar);
        assert file != null;
        userAvatar.setRealName(file.getName());
        // base64
        String filePath = file.getPath();
        userAvatar.setRealName(org.apache.commons.codec.binary.Base64.encodeBase64String(filePath.getBytes(StandardCharsets.UTF_8)));
        userAvatar.setPath("avic/file/tmp/avatar/");
        userAvatar.setSize(FileUtil.getSize(multipartFile.getSize()));
        userAvatarService.saveOrUpdate(userAvatar);
        user.setAvatarId(userAvatar.getId());
        this.saveOrUpdate(user);
        if (StringUtils.isNotBlank(oldPath)) {
            FileUtil.del(oldPath);
        }
    }

    /**
     * 修改邮箱
     *
     * @param username 用户名
     * @param email    邮箱
     */
    @Override
    public void updateEmail(String username, String email) {
        userMapper.updateEmail(email, username);
    }

    /**
     * 新增用户
     *
     * @param resources /
     * @return /
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean create(User resources) {

        if(resources.getDeptId()==null){
            throw new BadRequestException("所属部门不能为空");
        }

        User jobNumber = this.getOne(new LambdaQueryWrapper<User>()
                .eq(User::getJobNumber, resources.getJobNumber()));
        if (jobNumber != null) {
            throw new BadRequestException("工号已存在");
        }

        boolean matches1 = resources.getUsername().matches("[a-zA-Z0-9_.,\\-()/=+?!*;@#:%\\[\\]‘\\\\${}^|~\\n\\r\\t ]{1,35}");
        if(!matches1){
            throw new BadRequestException("用户名不能包含汉字");
        }

        User userName = this.getOne(new LambdaQueryWrapper<User>()
                .eq(User::getUsername, resources.getUsername()));
        if (userName != null) {
            throw new BadRequestException("用户名已存在");
        }

        if(resources.getPhone()!=null && resources.getPhone()!="" ){
            boolean matches = resources.getPhone().matches("^1[3-9]\\d{9}$");
            if(!matches){
                throw new BadRequestException("请输入正确的手机号");
            }
        }

        resources.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        resources.setCreateTime(new Timestamp(System.currentTimeMillis()));
        resources.setCreateUserId(SecurityUtils.getUserId());
        boolean result = this.save(resources);
        UsersRoles usersRoles = new UsersRoles();
        usersRoles.setUserId(resources.getId());
        Set<Role> set = resources.getRoles();
        for (Role roleIds : set) {
            if(roleIds!=null) {
                usersRoles.setRoleId(roleIds.getId());
                usersRolesService.save(usersRoles);
            }
        }
        // 创建操作日志
        LogVo logVo = new LogVo();
        String name = "[添加]了"+ " [" + resources.getUsername()+ "] " + "用户信息";
        logVo.setBehavior(name);
        logVo.setAction(LogEnumeration.Add_TO.getMessage());
        logsService.save(logVo);

        return result;
    }

    /**
     * 编辑用户
     *
     * @param resources /
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(User resources) {

        if(resources.getDeptId()==null){
            throw new BadRequestException("所属部门不能为空");
        }

        boolean matches1 = resources.getUsername().matches("[a-zA-Z0-9_.,\\-()/=+?!*;@#:%\\[\\]‘\\\\${}^|~\\n\\r\\t ]{1,35}");
        if(!matches1){
            throw new BadRequestException("用户名不能包含汉字");
        }

        User user = this.getOne(new LambdaQueryWrapper<User>()
                .eq(User::getId, resources.getId()));

        User user1 = this.getOne(new LambdaQueryWrapper<User>()
                .eq(User::getUsername, resources.getUsername()));

        User jobNumber = this.getOne(new LambdaQueryWrapper<User>()
                .eq(User::getJobNumber, resources.getJobNumber()));

        if (jobNumber != null ) {
            if(!user.getId().equals(jobNumber.getId())){
                throw new BadRequestException("工号已存在");
            }

        }
        if (user1 != null) {
            if(!user.getId().equals(user1.getId())){
                throw new BadRequestException("当前用户名已存在");
            }
        }

        if(resources.getPhone()!=null && resources.getPhone()!=""){
            boolean matches = resources.getPhone().matches("^1[3-9]\\d{9}$");
            if(!matches){
                throw new BadRequestException("请输入正确的手机号");
            }
        }

        // 修改后过滤数据
        UserVo sysUserVo = new UserVo();
        sysUserVo.setName(resources.getUsername());
        sysUserVo.setFullName(resources.getNickName());
        sysUserVo.setJobNumber(resources.getJobNumber());
        sysUserVo.setPhone(resources.getPhone()!=null?resources.getPhone():null);
        if(resources.getWorkStage()!=null){
            WorkshopSection paragraph = workshopSection.selectById(resources.getWorkStage());
            sysUserVo.setWorkshopName(paragraph!=null?paragraph.getName():null);
        } else {
            sysUserVo.setWorkshopName(null);
        }

        if(resources.getEnabled()){
            sysUserVo.setSignState("激活");
        }else {
            sysUserVo.setSignState("禁用");
        }

        // 修改前过滤数据
        UserVo userVo = new UserVo();
        userVo.setName(user.getUsername());
        userVo.setFullName(user.getNickName());
        userVo.setJobNumber(user.getJobNumber());
        userVo.setPhone(user.getPhone()!=null?user.getPhone():null);
        if(user.getWorkStage()!=null){
            WorkshopSection paragraph = workshopSection.selectById(user.getWorkStage());
            userVo.setWorkshopName(paragraph!=null?paragraph.getName():null);
        }else {
            userVo.setWorkshopName(null);
        }

        if(user.getEnabled()){
            userVo.setSignState("激活");
        }else {
            userVo.setSignState("禁用");
        }

        // 修改前
        Dept dept = deptMapper.selectById(user.getDeptId());
        userVo.setDeptName(dept!=null?dept.getName():null);

        Job job = jobMapper.selectById(user.getJobId());
        userVo.setJobName(job!=null?job.getName():null);

        Set<Role> byUsers_id = roleMapper.findByUsers_Id(user.getId());
        String roleName2 = "";
        for(Role by:byUsers_id){
            roleName2 += by.getName() + ",";
        }
        userVo.setRoleName(roleName2);

        // 修改后
        Dept dept2 = deptMapper.selectById(resources.getDeptId());
        sysUserVo.setDeptName(dept2.getName());

        Job job2 = jobMapper.selectById(resources.getJobId());
        if(job2!=null){
            sysUserVo.setJobName(job2.getName());
        } else {
            sysUserVo.setJobName(null);
            resources.setJobId(0L);
        }


        resources.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        resources.setUpdateUserId(SecurityUtils.getUserId());
        boolean result = this.saveOrUpdate(resources);
        usersRolesService.lambdaUpdate().eq(UsersRoles::getUserId, resources.getId()).remove();
        UsersRoles usersRoles = new UsersRoles();
        usersRoles.setUserId(resources.getId());
        Set<Role> set = resources.getRoles();
        String roleName = "";
        for (Role roleIds : set) {
            if(result){
                Role role = roleMapper.selectById(roleIds.getId());
                usersRoles.setRoleId(roleIds.getId());
                roleName += role.getName() + ",";
                usersRolesService.save(usersRoles);
            }

        }
        sysUserVo.setRoleName(roleName);

        // 创建操作日志
        String s = ContrastObjUtil.comparObj(sysUserVo,userVo);
        LogVo logVo = new LogVo();
        String name = "[修改]了"+ " [" + user.getUsername() + "] " + "用户信息 ";
        logVo.setBehavior(name);
        logVo.setInformation(s);
        logVo.setAction(LogEnumeration.MODIFY.getMessage());
        logsService.save(logVo);

        // 如果用户的角色改变了，需要手动清理下缓存
        if (!resources.getRoles().equals(user.getRoles())) {
            String key = "role::loadPermissionByUser:" + user.getUsername();
            redisUtils.del(key);
            key = "role::findByUsers_Id:" + user.getId();
            redisUtils.del(key);
        }
    }

    /**
     * 删除用户信息
     * @param ids
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Set<Long> ids) {
        List<String> strings = new ArrayList<>();
        for (Long id : ids) {
            usersRolesService.lambdaUpdate().eq(UsersRoles::getUserId, id).remove();
            User user = userMapper.selectById(id);
            strings.add(user.getUsername());
        }
        this.removeByIds(ids);

        // 创建操作日志
        LogVo logVo = new LogVo();
        String name = "[删除]了"+ " [" + strings.toString() + "] " +"用户信息";
        logVo.setBehavior(name);
        logVo.setAction(LogEnumeration.Delete.getMessage());
        logsService.save(logVo);
    }

    /**
     * 导入用户信息
     * @param file
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void userImport(MultipartFile file) {
        try {
            // 判断上传文件是否为空
            if(file==null){
                throw new BadRequestException("上传的文件不能是空的");
            }
            //获取文件名称
            String fileName = file.getOriginalFilename();
            //获取文件后缀名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));

            if(!suffixName.equalsIgnoreCase(".xls")&&!suffixName.equalsIgnoreCase(".xlsx")){
                throw new BadRequestException("文件格式不匹配");
            }

            // 把文件下载到默认路径
            String filePath = avicConfigElement.getAvatarLocation();
            String files = filePath + fileName;
            file.transferTo(new File(files));
            ExcelParser excelpaser = new ExcelParser(files);
            excelpaser.Read();
            Map<Integer,Integer> SheetNum = new HashMap<>();
            //设置要读取的工作表顺序号及其对应的行号
            SheetNum.put(1,1);
            List<ExcelBean> excelBeanList = excelpaser.GetExcelBean(SheetNum);
            List<User> dataMappings = new ArrayList<>();
            for(ExcelBean Eb:excelBeanList){
                List<Map<Integer, Object>> rowList = Eb.getRows();
                if(rowList.size()==0){
                    throw new BadRequestException("文件不能是空的");
                }
                for(Map<Integer, Object> map:rowList){
                    User user = new User();
                    user.setEnabled(false);
                    user.setIsDel(0);
                    Long userId = SecurityUtils.getUserId();
                    if(userId==null){
                        throw new BadRequestException("登录状态已过期");
                    }
                    user.setCreateUserId(userId);
                    user.setCreateTime(new Timestamp(System.currentTimeMillis()));

                    // 工号
                    String jobNumber = map.get(2).toString();
                    if(!jobNumber.equals("<BLANK>")){
                        QueryWrapper<User> wrapper = new QueryWrapper<>();
                        wrapper.eq("job_number",jobNumber);
                        User user1 = userMapper.selectOne(wrapper);
                        if(user1==null){
                            user.setJobNumber(jobNumber);
                        }else {
                            throw new BadRequestException(jobNumber+"工号已存在");
                        }
                    }else {
                        throw new BadRequestException("工号不能为空");
                    }

                    // 姓名
                    String nickName = map.get(3).toString();
                    if(!nickName.equals("<BLANK>")){
                        user.setNickName(nickName);
                    }else {
                        throw new BadRequestException("姓名不能为空");
                    }

                    // 部门
                    String dept = map.get(4).toString();
                    if(!dept.equals("<BLANK>")){
                        QueryWrapper<Dept> wraJob = new QueryWrapper<>();
                        wraJob.eq("name",dept);
                        Dept dept1 = deptMapper.selectOne(wraJob);
                        if(dept1==null){
                            throw new BadRequestException(dept1+"部门不存在");
                        }else {
                            user.setDeptId(dept1.getId());
                        }
                    }else {
                        throw new BadRequestException("部门不能为空");
                    }

                    // 岗位
                    String job = map.get(5).toString();
                    if(!job.equals("<BLANK>")){
                        QueryWrapper<Job> wraJob = new QueryWrapper<>();
                        wraJob.eq("name",job);
                        Job job1 = jobMapper.selectOne(wraJob);
                        if(job1==null){
                            throw new BadRequestException(job+"岗位不存在");
                        }else {
                            user.setJobId(job1.getId());
                        }
                    }

                    // 手机号
                    String phone = map.get(6).toString();
                    if(!phone.equals("<BLANK>")){
                        boolean matches = phone.matches("^1[3-9]\\d{9}$");
                        if(!matches){
                            throw new BadRequestException("请输入正确的手机号");
                        }
                        user.setPhone(phone);
                    }

                    // 工段
                    String workshop = map.get(7).toString();
                    if(!workshop.equals("<BLANK>")){
                        QueryWrapper<WorkshopSection> wraParagraph = new QueryWrapper<>();
                        wraParagraph.eq("name",workshop);
                        WorkshopSection paragraph = workshopSection.selectOne(wraParagraph);
                        if(paragraph==null){
                            throw new BadRequestException(workshop+"工段不存在");
                        }else {
                            user.setWorkStage(paragraph.getId());
                        }
                    }

                    // 用户名
                    String username = map.get(8).toString();
                    if(!username.equals("<BLANK>")){
                        boolean matches1 = username.matches("[a-zA-Z0-9_.,\\-()/=+?!*;@#:%\\[\\]‘\\\\${}^|~\\n\\r\\t ]{1,35}");
                        if(!matches1){
                            throw new BadRequestException("用户名不能包含汉字");
                        }
                        QueryWrapper<User> wraUser = new QueryWrapper<>();
                        wraUser.eq("username",username);
                        User user2 = userMapper.selectOne(wraUser);
                        if(user2!=null){
                            throw new BadRequestException(user2+"账号已存在");
                        }else {
                            user.setUsername(username);
                        }
                    }else {
                        throw new BadRequestException("用户名不能为空");
                    }

                    // 角色
                    String roleName = map.get(9).toString();
                    if(!roleName.equals("<BLANK>")){
                        QueryWrapper<Role> wraRole = new QueryWrapper<>();
                        wraRole.eq("name",roleName);
                        Role role = roleMapper.selectOne(wraRole);
                        if(role==null){
                            throw new BadRequestException(roleName+"角色不存在,请添加后再从新上传");
                        }else {
                            user.setRole(role.getId());
                        }
                    }

                    String password = map.get(10).toString();
                    if(!password.equals("<BLANK>")){
                        String encode = passwordEncoder.encode(password);
                        user.setPassword(encode);
                    }else {
                        String encode = passwordEncoder.encode("123456");
                        user.setPassword(encode);
                    }
                    dataMappings.add(user);
                    userMapper.insert(user);
                }
            }

            //添加角色
            for(User consumer:dataMappings){
                UsersRoles usersRoles = new UsersRoles();
                usersRoles.setRoleId(consumer.getRole());
                usersRoles.setUserId(consumer.getId());
                usersRolesMapper.insert(usersRoles);
            }
            excelpaser.Close();
            File file1 = new File(files);
            file1.delete();
            // 创建操作日志信息
            LogVo logVo = new LogVo();
            String name = "[导入]了" + "[用户管理信息]";
            logVo.setBehavior(name);
            logVo.setAction(LogEnumeration.IMPORT.getMessage());
            logsService.save(logVo);
        }catch (IOException e) {
            throw new BadRequestException("文件解析异常");
        } catch (NullPointerException e){
            throw new BadRequestException("参数格式不匹配");
        } catch (OfficeXmlFileException e) {
            throw new BadRequestException("文件解析错误");
        }
    }

}
